package com.springboot.uav.util;


import com.auth0.jwt.JWT;

import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * Created by IntelliJ IDEA.
 * &#064;Author : Zys
 * &#064;create 2024/11/13 17:30
 */
@Component
public class JWTUtil {
    // JWT加密解密的密钥
    private final String SECRET_KEY = "zys2022150156";
    private final String ISSUER = "DJ";
    private final long EXPIRATION =3600000;
    // token过期时间：24小时
    public String generateToken(String username,Integer userId){

        return JWT.create()
                .withIssuer(ISSUER)
                .withClaim("username", username)
                .withClaim("userId",userId)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION))
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }
    public String getUsernameFromToken(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);
        return decodedJWT.getClaim("username").asString();
    }
    public Integer getUserIdFromToken(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);
        return decodedJWT.getClaim("userId").asInt();
    }
    public boolean validateToken(String token){
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY))
                    .withIssuer(ISSUER)
                    .build();
            verifier.verify(token);  // 实际执行验证
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }




}
